﻿@using Microsoft.JSInterop

@inherits RadzenComponentWithChildren
@if (Visible)
{
    <div @ref="@Element" style="@Style" @attributes="Attributes" class="@GetCssClass()" id="@GetId()">
        <button disabled="@Disabled" class="@getButtonCss()" type="button" @onclick="@OnClick">
            @if (!string.IsNullOrEmpty(@Icon))
            {
                <i class="rz-button-icon-left rzi">@((MarkupString)Icon)</i>
            }
            @if (!string.IsNullOrEmpty(Image))
            {
                <img class="rz-button-icon-left rzi" src="@Image" />
            }
            @if (!string.IsNullOrEmpty(Text))
            {
                <span class="rz-button-text">@Text</span>
            }
            else
            {
                <span class="rz-button-text">&nbsp;</span>
            }
        </button><button onclick="@OpenPopupScript()" class="@getPopupButtonCss()" icon="rzi rzi-chevron-down" type="button">
            <span aria-hidden="true" class="rz-button-icon-left rzi rzi-chevron-down"></span><span class="rz-button-text ">rz-btn</span>
        </button>
        <div id="@PopupID" class="rz-splitbutton-menu">
            <ul class="rz-menu-list">
                <CascadingValue Value=this>
                    @ChildContent
                </CascadingValue>
            </ul>
        </div>
    </div>
}
@code {
    [Parameter]
    public string Text { get; set; } = "";

    [Parameter]
    public string Icon { get; set; }

    [Parameter]
    public string Image { get; set; }

    [Parameter]
    public bool Disabled { get; set; }

    [Parameter]
    public EventCallback<RadzenSplitButtonItem> Click { get; set; }

    public async System.Threading.Tasks.Task OnClick(MouseEventArgs args)
    {
        if (!Disabled)
        {
            await Click.InvokeAsync(null);
        }
    }

    public void Close()
    {
        JSRuntime.InvokeVoidAsync("Radzen.closePopup", PopupID);
    }

    private string PopupID
    {
        get
        {
            return $"popup{UniqueID}";
        }
    }

    private string getButtonCss()
    {
        return $"rz-button  rz-button-text-icon-left{(Disabled ? " rz-state-disabled" : "")}";
    }

    private string getPopupButtonCss()
    {
        return $"rz-splitbutton-menubutton rz-button rz-button-icon-only{(Disabled ? " rz-state-disabled" : "")}";
    }

    private string OpenPopupScript()
    {
        if (Disabled)
        {
            return string.Empty;
        }

        return $"Radzen.togglePopup(this.parentNode, '{PopupID}')";
    }

    protected override string GetComponentCssClass()
    {
        return Disabled ? "rz-splitbutton rz-buttonset rz-state-disabled" : "rz-splitbutton rz-buttonset";
    }
}
